package com.example.demo.service.impl;

import com.example.demo.dao.ProductDAO;
import com.example.demo.model.Paging;
import com.example.demo.model.Product;
import com.example.demo.param.BasePageParam;
import com.example.demo.service.ProductService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDAO productDAO;
    @Override
    public int save(Product product) {
        if (product.getId() == null) {
            product.setId(UUID.randomUUID().toString().replace("-", ""));
        }
        if (productDAO.selectById(product.getId()) == null) {
            return productDAO.insert(product.toDO());
        }else {
            return productDAO.updateById(product.toDO());
        }
    }

    @Override
    public Paging<Product> pageQueryProduct(BasePageParam param) {
        Page<Product> page= PageHelper.startPage(param.getPageNum(),param.getPageSize())
                .doSelectPage(()->productDAO.selectAll());
        return new Paging<>(page.getPageNum(),page.getPageSize(),page.getPages(),page.getTotal(),page.getResult());
    }

    @Override
    public Product get(String productId) {
        return productDAO.selectById(productId).toModel();
    }
}
